import { defineConfig, loadEnv, ConfigEnv, UserConfig } from "vite";
import react from "@vitejs/plugin-react";
import path from "path";
import { createHtmlPlugin } from "vite-plugin-html";
import legacy from "@vitejs/plugin-legacy";
import postcssPxtorem from "postcss-pxtorem";
import autoprefixer from "autoprefixer";
import postcssPresetEnv from "postcss-preset-env"; //use to support CSS variable and so on modern feature

type sourceMapType = boolean | "inline" | "hidden" | undefined;

// https://vitejs.dev/config/
export default defineConfig((arg: ConfigEnv) => {
  const { mode } = arg;
  const sourceMap: sourceMapType = mode == "development" ? "inline" : true;

  return {
    base: "/",
    plugins: [
      react(),
      createHtmlPlugin({
        inject: {
          data: {
            title: "my-new-vite",
            // injectScript: "../../config.js",//need reference config script，in html config: <script src="<%- injectScript %>"></script>
          },
        },
      }),
      legacy({
        targets: ["chrome 49"], //37 58 (默认配置下 iOS Safari >= 10 和 Chrome >= 49 为antdMobile最大兼容性)
        // additionalLegacyPolyfills: ["regenerator-runtime/runtime"], //when we face IE11, we need use this plugin
        // renderLegacyChunks: true, //当设置为true时，Vite会为旧浏览器生成独立的legacy chunk，而现代浏览器则加载包含原始代码的main chunk
        modernPolyfills: true, //通过转换语法和添加polyfills，确保旧浏览器能正确执行页面功能
      }),
    ],
    resolve: {
      extensions: [
        ".mjs",
        ".js",
        ".mts",
        ".ts",
        ".jsx",
        ".tsx",
        ".json",
        ".less",
      ],
      alias: {
        "@": path.resolve(__dirname, "src"),
        components: path.resolve(__dirname, "src/components"),
        state: path.resolve(__dirname, "src/state"),
      },
    },
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true, // allow use javascript expression in less document
          additionalData: `@import "@/global.less";`,
        },
      },
      postcss: {
        plugins: [
          postcssPresetEnv(),
          autoprefixer,
          postcssPxtorem({
            rootValue: 750 / 10, // UI设计稿的宽度/10
            unitPrecision: 5, // 转rem精确到小数点多少位
            propList: ["*"], // 需要转换的属性 *表示所有
            selectorBlackList: ["ignore"], // 不进行px转换的选择器
            replace: true, // 是否直接更换属性值，而不添加备用属性
            mediaQuery: false, // 是否在媒体查询的css代码中也进行转换
            minPixelValue: 0, // 设置要替换的最小像素值
          }),
        ],
      },
    },
    server: {
      host: "0.0.0.0",
      port: 3000,
      // cors: true,
      // // https: false,
      // // 代理跨域（mock 不需要配置，这里只是个事列）
      // proxy: {
      // 	"/api": {
      // 		target: "https://mock.mengxuegu.com/mock/62abda3212c1416424630a45", // easymock
      // 		changeOrigin: true,
      // 		rewrite: path => path.replace(/^\/api/, "")
      // 	}
      // }
    },
    build: {
      outDir: "dist",
      // target: ["es2015"], //注意：build 中的 target 最低支持 es2015,修改为 chrome 53 是无效的，legacy会覆盖目标版本。
      sourcemap: sourceMap,
      reportCompressedSize: false,
      chunkSizeWarningLimit: 500,
      rollupOptions: {
        output: {
          // Static resource classification and packaging
          chunkFileNames: "assets/js/[name]-[hash].js",
          entryFileNames: "assets/js/[name]-[hash].js",
          assetFileNames: "assets/[ext]/[name]-[hash].[ext]",
        },
      },
    },
  };
});
